package com.nidu.demo.web.system;

import com.alibaba.cola.dto.PageResponse;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson2.JSONArray;
import com.nidu.demo.base.BatchDeleteCmd;
import com.nidu.demo.common.enums.UserTypeEnum;
import com.nidu.demo.mail.api.SysMailLogService;
import com.nidu.demo.mail.dto.*;
import com.nidu.demo.security.util.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.List;

/**
 * 邮件日志管理
 *
 * @author auto
 */
@Tag(name = "管理后台 - 邮件日志")
@RestController
@RequestMapping("/system/mail-log")
@Validated
@RequiredArgsConstructor
public class SysMailLogController {

    private final SysMailLogService mailLogService;

    @Operation(summary = "发送邮件", description = "发送邮件并记录日志")
    @PostMapping("/send")
    @PreAuthorize("@ss.hasPermission('system:mail:send')")
    public Response sendMail(@RequestBody MailSendCmd cmd) {
        Long userId = SecurityUtils.getLoginUserId();
        Integer userType = UserTypeEnum.ADMIN.getType();
        return mailLogService.sendMail(userId, userType, cmd);
    }

    @Operation(summary = "重新发送邮件", description = "根据日志ID重新发送邮件")
    @PostMapping("/{id}/resend")
    @PreAuthorize("@ss.hasPermission('system:mail:send')")
    public Response resendMail(@PathVariable Long id) {
        return mailLogService.resendMail(id);
    }

    @Operation(summary = "删除邮件日志", description = "根据 ID 删除邮件日志")
    @DeleteMapping("/{id}")
    @PreAuthorize("@ss.hasPermission('system:mail-log:delete')")
    public Response deleteMailLog(@PathVariable Long id) {
        return mailLogService.delete(id);
    }

    @Operation(summary = "批量删除邮件日志", description = "根据 ID 列表删除多个邮件日志")
    @PostMapping("/batch")
    @PreAuthorize("@ss.hasPermission('system:mail-log:delete')")
    public Response deleteMailLogs(@RequestBody BatchDeleteCmd cmd) {
        List<Long> ids = JSONArray.parseArray(cmd.getDelete(), Long.class);
        return mailLogService.delete(new HashSet<>(ids));
    }

    @Operation(summary = "获取邮件日志详情", description = "根据 ID 获取邮件日志详细信息")
    @GetMapping("/{id}")
    @PreAuthorize("@ss.hasPermission('system:mail-log:query')")
    public SingleResponse<MailLogCO> getMailLogById(@PathVariable Long id) {
        return mailLogService.getById(id);
    }

    @Operation(summary = "分页查询邮件日志", description = "分页获取邮件日志信息")
    @GetMapping("/page")
    @PreAuthorize("@ss.hasPermission('system:mail-log:query')")
    public PageResponse<MailLogCO> pageMailLogs(MailLogPageQry qry) {
        return mailLogService.page(qry);
    }

}
